/**
 * @page 顶部按钮实现业务逻辑
 * @description 在卡片页面，如果需要添加打印菜单按钮，需要引入此JS，然后执行现在打印按钮并绑定Click事件即可
 * @author administrator
 * @time 2019-05-24
 */

/********************************** PAGE CODE REALIZE **************************************/
//JS依赖URL
var storeJS = "https://cdn.bootcss.com/store.js/1.3.20/store.min.js";
var underscoreJS = "https://cdn.bootcss.com/underscore.js/1.9.1/underscore-min.js";
var vueJS = "https://cdn.jsdelivr.net/npm/vue";
var easyJS = "http://erp.brc-beei.com:8082/cwbase/web/scripts/easyui/jquery.easyui.min.js";
var echartJS = "https://cdn.bootcss.com/echarts/4.2.1-rc1/echarts.js";
var requireJS = "https://cdn.bootcss.com/require.js/2.3.6/require.js";

//影像控件下载URL
var viewDownloadURL = "http://yx.brc.com.cn:8199/TIMS-Server/nc-jsp/downloadActivex.jsp";
var viewUploadURL = "http://yx.brc.com.cn:8199/TIMS-Server/nc-jsp/imageupload.jsp";
var viewLookoverURL = "http://yx.brc.com.cn:8199/TIMS-Server/tims.jsp";

//数字常量
var oneNumb = 1;
var twoNumb = 2;
var thrNumb = 3;

/**
 * @function JS获取URL参数值
 * @param name URL参数名称
 */
function urlParam(name) {
    try {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    } catch (e) {}
}

/**
 * @function 加载JS/CSS脚本
 * @param filename 待加载脚本名称
 * @param filetype 待加载脚本类型（JS/CSS）
 */
function loadScript(filename, filetype) {

    try {

        if (filetype == null || filetype == undefined) {
            if (filename.lastIndexOf(".js")) {
                filetype = 'js';
            } else if (filename.lastIndexOf(".css")) {
                filetype = 'css';
            } else {
                filetype = '';
            }
        }

        if (filetype == "js") { //if filename is a external JavaScript file
            var fileref = document.createElement('script')
            fileref.setAttribute("type", "text/javascript")
            fileref.setAttribute("src", filename)
        } else if (filetype == "css") { //if filename is an external CSS file
            var fileref = document.createElement("link")
            fileref.setAttribute("rel", "stylesheet")
            fileref.setAttribute("type", "text/css")
            fileref.setAttribute("href", filename)
        }

        if (typeof fileref != "undefined")
            document.getElementsByTagName("head")[0].appendChild(fileref);

    } catch (e) {}

}

/**
 * @function 将关闭按钮移动到最后
 */
function btnMoveOption(toolbarid) {

    try {

        var closeBtn = $("div[toolbarid='" + toolbarid + "']").prop("outerHTML");
        var parentDiv = $("div[toolbarid='" + toolbarid + "']").parent();
        $("div[toolbarid='" + toolbarid + "']").remove();

    } catch (e) {

    }

}

/**
 * @function 加载图片函数
 */
function loadImage(wTableID, mainKeyField, imageField, rectify) {
    try {

        //如果是整改页面，则只对第一个附件上传输入框进行图片展示；如果是查看页面，则对多个附件上传输入框进行图片展示
        if ($('#hidopertype').val() == 'edit' && rectify == false) {
            imageField = 'none';
        } else if ($('#hidopertype').val() == 'view') {
            //设置展示图片字段为all
            imageField = "all";
        }

        if (typeof setupImage === 'function') {
            setupImage(imageField, wTableID, mainKeyField, 1);
        }

    } catch (e) {

    }
}

/**
 * @function 展示加载图片按钮
 */
function displayLoadImageButton() {

    try {

    } catch (error) {

    }

}

/**
 * @function 展示顶部打印菜单按钮
 */
function displayCloseButton() {

    try {

        setTimeout(function() {

            //需要展示的顶部菜单ITEM
            var btnitem = [];
            btnitem.push({ text: '关闭', icon: 'logout', id: 'close' });

            //在ID为buttonbar的div中初始化对应的顶部菜单
            $('#buttonbar').ligerToolBar({ items: btnitem });

            //顶部按钮设置点击事件
            $('#buttonbar').ligerGetToolBarManager().setClick('close', function() {
                if (typeof closeurl === 'function') {
                    closeurl();
                } else {
                    window.close();
                }
            });

        }, 0);

    } catch (e) {}

}

/**
 * @function 展示顶部打印菜单按钮
 */
function displayPrintButton() {

    try {

        setTimeout(function() {

            //需要展示的顶部菜单ITEM
            var btnitem = [];
            btnitem.push({ text: '打印', icon: 'print', id: 'printWeb' });

            //在ID为buttonbar的div中初始化对应的顶部菜单
            $('#buttonbar').ligerToolBar({ items: btnitem });

            //顶部按钮设置点击事件
            $('#buttonbar').ligerGetToolBarManager().setClick('printWeb', function() {
                if (typeof printWeb === 'function') {
                    printWeb();
                }
            });

        }, 0);


    } catch (e) {}

}

/**
 * @function 展示顶部审批菜单按钮
 */
function displayApprovalButton() {

    try {

        setTimeout(function() {

            //如果不是查看页面，则添加提交审批、取消审批按钮
            if ($('#hidopertype').val() != 'view') {

                wf = new GSIDP_API.WorkFlow($('#hidstyle').val());

                $('#buttonbar').ligerGetToolBarManager().addItem({
                    text: '提交审批',
                    icon: 'ok',
                    id: 'btnwfs',
                    click: function() {
                        if (typeof wfSumbit === 'function') {
                            return wfSumbit();
                        } else {
                            return function() {};
                        }
                    }
                });

                $('#buttonbar').ligerGetToolBarManager().addItem({
                    text: '取消审批',
                    icon: 'back',
                    id: 'btnwfc',
                    click: function() {
                        if (typeof wfCancel === 'function') {
                            return wfCancel();
                        } else {
                            return function() {};
                        }
                    }
                });
            }

        }, 0);


    } catch (e) {}

}

/**
 * @function 展示提交审批菜单按钮
 */
function displaySubmitApprButton() {

    try {

        setTimeout(function() {

            wf = new GSIDP_API.WorkFlow($('#hidstyle').val());

            $('#buttonbar').ligerGetToolBarManager().addItem({
                text: '提交审批',
                icon: 'ok',
                id: 'btnwfs',
                click: function() {
                    if (typeof wfSumbit === 'function') {
                        return wfSumbit();
                    } else {
                        return function() {};
                    }
                }
            });

        }, 0);


    } catch (e) {}
}

/**
 * @functIon 展示取消审批菜单按钮
 */
function displayCancelApprButton() {

    try {

        setTimeout(function() {

            wf = new GSIDP_API.WorkFlow($('#hidstyle').val());

            $('#buttonbar').ligerGetToolBarManager().addItem({
                text: '取消审批',
                icon: 'back',
                id: 'btnwfc',
                click: function() {
                    if (typeof wfCancel === 'function') {
                        return wfCancel();
                    } else {
                        return function() {};
                    }
                }
            });

        }, 0);

    } catch (e) {}

}

/**
 * @function 展示顶部菜单按钮
 */
function displaySomeButton() {

    try {

        setTimeout(function() {

            //需要展示的顶部菜单ITEM
            var btnitem = [];

            btnitem.push({ text: '提交审批', icon: 'ok', id: 'btnwfs' });
            btnitem.push({ text: '取消审批', icon: 'back', id: 'btnwfc' });
            btnitem.push({ text: '打印', icon: 'print', id: 'printNew' });
            btnitem.push({ text: '审批日志', icon: 'search', id: 'viewLogNew' });

            //在ID为buttonbar的div中初始化对应的顶部菜单
            $('#buttonbar').ligerToolBar({ items: btnitem });

            //设置工作流状态
            wf = new GSIDP_API.WorkFlow($('#hidstyle').val());

            //对相应的顶部菜单绑定点击事件
            $('#buttonbar').ligerGetToolBarManager().setClick('btnwfs', function() {
                if (typeof wfSumbit === 'function') {
                    return wfSumbit();
                }
            });

            $('#buttonbar').ligerGetToolBarManager().setClick('btnwfc', function() {
                if (typeof wfCancel === 'function') {
                    return wfCancel();
                }
            });

            $('#buttonbar').ligerGetToolBarManager().setClick('printNew', function() {
                if (typeof printWeb === 'function') {
                    printWeb();
                }
            });

            $('#buttonbar').ligerGetToolBarManager().setClick('viewLogNew', function() {
                if (typeof printWeb === 'function') {
                    viewLogNew();
                }
            });

        }, 0);

    } catch (e) {}

}

/**
 * @function 展示顶部常用菜单按钮
 */
function displayCommonButton() {

    //复用displaySomeButton函数
    displaySomeButton();

}

/**
 * @function 展示顶部影像查看菜单按钮
 */
function displayShowButton() {

    try {

        setTimeout(function() {

            //需要展示的顶部菜单ITEM
            var btnitem = [];
            btnitem.push({ text: '影像查看', icon: 'ok', id: 'btnShow' });

            //在ID为buttonbar的div中初始化对应的顶部菜单
            $('#buttonbar').ligerToolBar({ items: btnitem });

            //顶部按钮设置点击事件
            $('#buttonbar').ligerGetToolBarManager().setClick('btnShow', function() {
                if (typeof view === 'function') {
                    view();
                } else if (typeof viewLookover === 'function') {
                    viewLookover();
                }
            });

        }, 0);


    } catch (e) {}

}

/**
 * @function 展示顶部影像上传菜单按钮
 */
function displayShowUploadButton() {

    try {

        setTimeout(function() {

            //需要展示的顶部菜单ITEM
            var btnitem = [];
            btnitem.push({ text: '影像上传', icon: 'ok', id: 'btnShowUpload' });

            //在ID为buttonbar的div中初始化对应的顶部菜单
            $('#buttonbar').ligerToolBar({ items: btnitem });

            //顶部按钮设置点击事件
            $('#buttonbar').ligerGetToolBarManager().setClick('btnShowUpload', function() {
                if (typeof upload === 'function') {
                    upload();
                } else if (typeof viewUpload === 'function') {
                    viewUpload();
                }
            });

        }, 0);

    } catch (e) {}

}

/**
 * @function 展示顶部保存菜单按钮
 */
function displaySaveButton() {

    try {

        setTimeout(function() {

            //需要展示的顶部菜单ITEM
            var btnitem = [];
            btnitem.push({ text: '保存', icon: 'save', id: 'btnSave' });

            //在ID为buttonbar的div中初始化对应的顶部菜单
            $('#buttonbar').ligerToolBar({ items: btnitem });

            //顶部按钮设置点击事件
            $('#buttonbar').ligerGetToolBarManager().setClick('btnSave', function() { barbtnclk('btnsave', '') });

        }, 0);

    } catch (e) {};

}

/**
 * @function 展示顶部保存菜单按钮
 */
function displayViewLogButton() {

    try {

        setTimeout(function() {

            //需要展示的顶部菜单ITEM
            var btnitem = [];
            btnitem.push({ text: '审批日志', icon: 'search', id: 'viewLogNew' });

            //在ID为buttonbar的div中初始化对应的顶部菜单
            $('#buttonbar').ligerToolBar({ items: btnitem });

            //顶部按钮设置点击事件
            $('#buttonbar').ligerGetToolBarManager().setClick('viewLogNew', function() {
                if (typeof viewLogNew === 'function') {
                    viewLogNew();
                }
            });

        }, 0);

    } catch (e) {}

}

/**
 * @function 展示审批日志菜单按钮
 */
function viewLogNew() {

    try {

        var wf = new GSIDP_API.WorkFlow($('#hidstyle').val());

        if (typeof(wf.p_Field) == 'undefined') {
            TipHelp('没有进入审批流，不能查看流程信息!');
            return;
        }

        var proceeValue = getLoadValue()[wf.p_Field];
        var keyFieldValue = getLoadValue()[mainKeyField];

        if (!proceeValue) {
            proceeValue = DealAjax.execSelectSql(dbSaveSrc, Base64.encode("select " + wf.p_Field + " from " + mainTableName + " where " + mainKeyField + "='" + keyFieldValue + "'"), 'str');
        }

        if (!proceeValue) {
            TipHelp('没有进入审批流，不能查看流程信息!');
            return;
        }

        var INSTANCEID = GSIDPSession['GENERSOFT.BS.PUBLIC.GSAPPINSTANCEID'];
        var userID = GSIDPSession['GENERSOFT.BS.PUBLIC.USERID'];
        var UserCode = GSIDPSession['GENERSOFT.BS.PUBLIC.USER'];

        var url = "/cwbase/web/session/gspadp/viewWfPro.html?userId=" + userID + "&userCode=" + UserCode + "&appInstanceCode=" + INSTANCEID + "&procInstanceID=" + proceeValue;

        if (typeof openWorkFlowLog === 'function') {
            openWorkFlowLog(proceeValue, "查看审批日志", url);
        } else if (typeof openurl === 'function') {
            openurl(proceeValue, "查看审批日志", url);
        }

    } catch (e) {}

}


/**
 * @function 获取表单格式化样式列表
 */
function getFormatList(sqlID) {
    try {
        var vsData = DealAjax.getJsonDataTable(null,
            "Print_BillFormat",
            "BillID,FormatID",
            " AND BillID='" + sqlID + "'").Rows;
        return vsData;
    } catch (e) {}
}

/**
 * @function 打印页面函数
 */
function printWeb() {

    try {

        var self = this;

        //获取付款申请表对应主键ID
        var idValue = $("#" + mainKeyField).val();

        //获取SQLID
        var sqlID = urlParam('styleid');

        //获取打印格式列表
        var vsData = getFormatList(sqlID);

        //打印下拉框待填入值
        var data = [];

        //如果打印格式列表长度为0，则弹出提示
        if (vsData.length < 1) {
            $.ligerDialog.tip({ title: '提示', content: "请选择打印格式！" });
        }

        //遍历vsData，放入打印格式数据
        $.each(vsData, function(i, obj) {
            data.push({ "id": obj.FORMATID, "text": obj.FORMATID });
        });

        var html = $("<div></div>");
        var combox = $("<div style='overflow:auto;position:relative;margin-left:10px;margin-top:10px;'><input type='text' style='width:260px;' id='cmb_print_sel' class='comboxprint'></input></div>");
        var printoptions = $("<div style='position:relative;margin-left:10px;margin-top:10px;'><div style='font-weight:bold;'>" + langobj.get("PrintFormat") + "</div><div style='margin-top:8px; height: 30px;line-height: 24px;'><input class='magic-radio' type='radio' id='c1' name='printtype' checked='checked' value='pdf' ><label for='c1'>pdf</label> </div><div style=' height: 30px;line-height: 24px;'><input class='magic-radio' type='radio' id='c2' name='printtype' value='html' ><label for='c2'>html</label></input></div></div>");

        html.append(combox).append(printoptions);

        //打开打印对话框
        var dialog = $.ligerDialog.open({
            title: '选择打印格式',
            name: 'printselector',
            width: "300",
            height: "250",
            target: html,
            onclose: function() { html.remove(); },
            buttons: [{ text: '确定', onclick: btn_printok }, { text: '取消', onclick: btn_printcancel }]
        });

        //设置打印格式下拉框列表的值
        $("#cmb_print_sel").val(data[0]["id"]);
        $("#cmb_print_sel").ligerComboBox({
            data: data
        });

    } catch (e) {}

    /**
     * @function 打印取消函数
     */
    function btn_printcancel() {
        try {
            dialog.close();
        } catch (e) {}
    }

    /**
     * @function 打印确定函数
     */
    function btn_printok() {

        try {

            //加载中
            var styleid = sqlID;
            var dtsrc = dbSaveSrc;
            var dataid = idValue;
            var formatid = $("#cmb_print_sel").val();
            var type = $("input[name='printtype']:checked").val();

            if (formatid == "") {
                $.ligerDialog.tip({ title: '提示', content: "请选择打印格式！" });
                return;
            }

            printFormat(dtsrc, styleid, formatid, type, dataid, function(data) {
                window.open(data["file"]);
                dialog.close();
            });

        } catch (e) {}

    }

}

/**
 * @function 打开审批日志函数
 * @param id 
 * @param name 
 * @param url 
 */
function openWorkFlowLog(id, name, url, isrtf, reload) {
    try {
        if (url.indexOf('/') != 0 && url.toLowerCase().indexOf('http://') != 0)
            url = "/cwbase/web/session/GSIDP/GSYS/WEB/" + url;
        if (!isrtf) {
            id = id + (new Date()).getTime();
        }
        var isInWinfrom = ('external' in window) && ('GetSession' in window.external);
        if (isInWinfrom) {
            window.external.OpenFuncForWeb(id, name, url, reload || false);
            return;
        }
        if (window.top.gsp && window.top.gsp.rtf.allFunc) {
            var ops = { "id": id, "name": name, "url": url };
            window.parent.top.gsp.rtf.allFunc.openUrl(ops); //.rtf.func.openUrl(ops); 
            return;
        }
        window.open(url);
    } catch (e) {
        window.open(url);
    }
}

/**
 * @function 关闭页面
 */
function closeurl() {
    var bl = false;
    try {
        if (window.top.gsp && window.top.gsp.rtf.allFunc) {
            window.top.gsp.rtf.allFunc.close($.url.param('funcid'));
            bl = true;
        }
    } catch (e) {}

    if (!bl) {
        var pwin = window.parent;
        while (pwin != pwin.parent) {
            pwin = pwin.parent;
        }
        if (window.opener == undefined) {
            window.opener = null;
            window.open("", "_self");
        }
        if (pwin == window) {
            window.close();
        } else {
            pwin.close();
        }
    }
}

/**
 * @function 打印格式函数
 * @param dtsrc 
 * @param styleid 
 * @param formatid 
 * @param type 
 * @param value 
 * @param callback 
 * @param replace 
 */
function printFormat(dtsrc, styleid, formatid, type, value, callback, replace) {

    try {
        var vsJsonData = {
            formatid: formatid,
            dataid: value,
            styleid: styleid,
            dtsrc: dtsrc,
            replace: replace,
            type: type
        };

        $.ajax({
            url: _gsidashxfolder + "/WF/printweb.ashx",
            type: "post",
            data: vsJsonData,
            dataType: "json",
            async: true,
            success: function(reval) {
                if (reval["isok"]) {
                    callback.call(this, reval);
                } else {
                    $.ligerDialog.success(reval["mes"]);
                }
            },
            error: function(err) {
                throw err.responseText;
                return false;
            }
        });
    } catch (e) {}

}

/**
 * @function 为每行附件框设置展示图片
 */
function setupImage(name, wTableID, mainKeyID, maxCount) {

    //捕获异常，避免异常后JS停止执行
    try {

        if (name != 'none') {

            //记录此函数遍历次数
            if (window.scount == null || window.scount == undefined) {
                window.scount = 0;
            }

            if (maxCount == null || maxCount == undefined) {
                maxCount = 0;
            }

            //获取附件上传按钮的个数
            var isLoad = $("#grid_" + wTableID + "grid").find('.l-grid-row-cell a').length;

            //如果附件上传按钮的个数大于0，则进行设置图片展示功能
            if (isLoad != null && isLoad != undefined && isLoad > 0) {

                //设置行记录高度
                $("#grid_" + wTableID + "grid").find('.l-grid-row-cell').css('height', '120');

                if (name == "all") {
                    $("#grid_" + wTableID + "grid").find('.l-grid-row-cell a').each(function() {
                        changeHtml(this, mainKeyID);
                    });
                } else {
                    //遍历每行记录的附件框，并设置图片展示
                    $("#grid_" + wTableID + "grid td[id$='" + name + "']").each(function() {

                        //获取对应HTML标签下面的A标签
                        var item = $(this).find('a');

                        //改变对应附件框的HTML的内容
                        changeHtml(item, mainKeyID);

                    });
                }

            } else {

                //为避免执行次数过多，设置最多3次设置展示图片操作
                if (window.scount++ <= maxCount) {
                    //问题清单显示后，设置展示图片
                    setTimeout(function() {
                        //设置展示图片
                        setupImage(name, wTableID, mainKeyID, --maxCount);
                    }, 1500 * window.scount);
                }

            }

        }

    } catch (e) {

    }
}

/**
 * @function 修改对应输入框HTML内容
 * @param selector 
 */
function changeHtml(selector, mainKeyID) {

    var href = $(selector).attr('href');
    var info = "";
    var url = "/cwbase/web/session/GSIDP/GSYS/WEB/GSYDownLoadFile.aspx?id={GSYFILESAVE_ID}";
    var fieldName = mainKeyID.split('_')[0] + '_';

    if (href != null && href != undefined) {

        //获取对应清单记录信息
        vscript = href.toString();
        href = href.replace("javascript:openGridFile(", "");
        href = href.substring(0, href.length - 1);
        info = JSON.parse("[" + href + "]");
        fieldName = fieldName + $(selector).parent().parent().parent().attr('id').split(fieldName)[1];

        //查询对应记录的图片信息
        var pictures = DealAjax.getJsonDataTable(dbSaveSrc,
            'GSYFILESAVE',
            'GSYFILESAVE_ID , GSYFILESAVE_PATH , GSYFILESAVE_FILENAME',
            " AND GSYFILESAVE_REFKEY = '" + info[0][mainKeyID] + "' AND GSYFILESAVE_FIELDID = '" + fieldName + "' AND GSYFILESAVE_EXT IN ('.jpg' , '.JPG' , '.jpeg' ,  '.JPEG' ,  '.png' , '.PNG' , '.bmp' , '.BMP' , '.tif' ,  '.TIF' , '.ico' , '.ICO' , '.gif' , '.GIF' ) ");

        if (pictures && pictures.Rows && pictures.Rows.length > 0) {

            var details = '';

            //遍历数组
            pictures.Rows.forEach(function(item) {
                details = details + ',' + item['GSYFILESAVE_ID'];
            });

            var iurl = url.replace("{GSYFILESAVE_ID}", pictures.Rows[0]['GSYFILESAVE_ID']);
            $(selector).parent().parent().parent().html("<a href='javascript:viewFile(\"" + pictures.Rows[0]['GSYFILESAVE_ID'] + "\" , \"" + fieldName + "\" , \"" + details + "\" )' >" + '<img  style="max-height:115px;max-width:181px;" src="' + iurl + '" alt=""></a>');
        }
    }
}

/**
 * @function 查看附件Dialog
 * @param id 图片GUID 
 */
function viewFile(id, fieldID, details, mkid) {

    if (typeof(mkid) == 'undefined' || typeof(mkid) == "null") {
        mkid = 'PMQM';
    }
    if (typeof(details) == 'undefined' || typeof(details) == "null") {
        details = '';
    }
    if (typeof(fieldID) == 'undefined' || typeof(fieldID) == "null") {
        fieldID = '';
    }

    var urlview = "/cwbase/web/session/GSIDP/GSYS/WEB/GSYDocOfficeCtrl.aspx?FileName=&EXT=&id=" + id + "&MKID=" + mkid + "&FIELDID=" + fieldID + "&filepath=";
    var winwidth = $(window).width() - 100;
    var winheight = $(window).height() - 80;

    //打开对应图片Dialog窗口
    window.$.ligerDialog.open({
        title: "查看附件",
        name: 'viewdoc',
        isHidden: false,
        showMax: true,
        width: winwidth,
        height: winheight,
        url: urlview
    });

    //等待Dialog窗口打开完毕后，执行删除多余图片操作
    setTimeout(function() {

        //页面加载完毕后，需要去掉不需要的图片
        $("#viewdoc").contents().find('.listView').each(function() {

            //获取对应图片ID
            var id = $(this).attr('dsid');

            //如果views中不存在对应的ID值，则删除相应的图片
            if (details.indexOf(id) < 0) {
                $(this).remove();
            }
        });

    }, 1500);

    return false;
}

/**
 * @function 删除附件图片函数
 * @param id 图片GUID 
 */
function deleteFile(id, path, mkid) {

    if (typeof(mkid) == 'undefined' || typeof(mkid) == "null") {
        mkid = 'PMQM';
    }
    if (typeof(path) == 'undefined' || typeof(path) == "null") {
        path = '';
    }

    var objre = DealAjax.remoteDeleteData(null,
        "GSYFILESAVE", {
            "delfield": "GSYFILESAVE_ID,GSYFILESAVE_MKID,GSYFILESAVE_PATH",
            "delvalue": id + "," + mkid + "," + path
        },
        '',
        '../../GSYS/WEB/RemoteDeleteOneFileData.ashx');
    if (objre.Result) {
        window.parent.TipHelp("删除成功！");
    }
}

/**
 * @function 下载附件图片函数
 * @param id 
 */
function download(id, mkid) {

    if (typeof(mkid) == 'undefined' || typeof(mkid) == "null") {
        mkid = 'PMQM';
    }

    var url = "../../GSYS/WEB/GSYFileDownLoad.aspx?MKID=" + mkid + "&GUID=" + id;

    function getiframeDocument($iframe) {
        var iframeDoc = $iframe[0].contentWindow || $iframe[0].contentDocument;
        if (iframeDoc.document) {
            iframeDoc = iframeDoc.document;
        }
        return iframeDoc;
    }

    var $iframe = $("<iframe style='display: none' src='about:blank'></iframe>").appendTo("body");
    $iframe.ready(function() {
        var formDoc = getiframeDocument($iframe);
        formDoc.write("<html><head></head><body><form method='Post' action='" + url + "'></form></body></html>");
        var $form = $(formDoc).find('form');
        $form.submit();
    });

    return false;
}


/**
 * @function 影像控件下载
 * @description 请确保调用前，已经设置第三方识别唯一ID（window.thirdCode）
 */
function viewDownload() {

    //影像控件下载URL
    var viewURL = viewDownloadURL;

    //浏览器打开影像控件下载URL
    window.open(viewURL, "_blank");
}

/**
 * @function 影像上传
 * @description 请确保调用前，已经设置第三方识别唯一ID（window.thirdCode）
 */
function viewUpload() {

    if (typeof thirdCode != 'undefined') {

        //第三方识别唯一ID
        var def3 = $(window.thirdCode).val();

        //影像上传URL
        var uploadURL = "TURLProtocol:" + viewUploadURL + "?pk_jkbx=" +
            def3 + "&scanType=1&modulename=EAS&tradtypeName=image&billNo=" +
            def3 + "&detailInfo=detailInfo&orgNo=0&dept_id=0&billtype=2641&systemCode=EAS&saveopt=0&savestep=1&1";

        //浏览器打开影像上传URL
        window.open(uploadURL, "_blank");

    }
}

/**
 * @function 影像查看
 * @description 请确保调用前，已经设置第三方识别唯一ID（window.thirdCode）
 */
function viewLookover() {

    if (typeof thirdCode != 'undefined') {
        //第三方识别唯一ID
        var def3 = $(window.thirdCode).val();

        //影像查看URL
        var viewURL = viewLookoverURL + "?pk=" + def3 + "&isEdit=0";

        //浏览器打开影像查看URL
        window.open(viewURL, "_blank");
    }

}

/**
 * @function Checkbox点击事件，同一属性，Checkbox只能选择一个
 */
function checkSingle() {

    //checkbox绑定Click事件
    $(":checkbox").click(function() {
        if ($(this).attr("checked") != undefined) {
            var id = $(this).attr('id');
            $(this).siblings().attr("checked", false);
            $('[id^=' + id.substring(0, id.length - 1) + "]").attr("checked", false);
            $(this).attr("checked", true);
        }
    });

}

/**
 * @function checkRight,设置特定字段输入框的权限(是否只读)
 */
function checkRight(flag, fields, operation) {

    //设置对应操作码
    operation = (flag != true) ? 'disa' : true;

    //遍历数组，设置特定字段的权限
    fields.forEach(function(element) {
        setCardCtrlEnabled(element, operation);
    });

}

/**
 * @function checkRequired,设置特定字段输入框是否为必选项
 */
function checkRequired(flag, fields, operation) {

    //设置对应操作码
    operation = (flag != true) ? false : true;

    //遍历数组，设置特定字段的权限
    fields.forEach(function(element) {
        dealRequiredValid(element, operation);
    });

}

/**
 * @function 处理权限设置问题
 * @param flag true false true：表示具有读写权限；false：表示没有读写权限
 * @param name process的参数值
 */
function process(flag, name, count) {

    if (typeof(count) == 'undefined' || typeof(count) == 'null') {
        count = 0;
    }
    if (typeof(name) == 'undefined' || typeof(name) == 'null') {
        name = $.url.param('process');
    }

    //招标评价审核表（设计）的权限设置
    if ((name == 'ZBSJ_JY') == flag) {
        checkRight(flag, ['PMZBWJPSB_FBRZX', 'PMZBWJPSB_WJWZX', 'PMZBWJPSB_JYBZ']);
    }
    if ((name == 'ZBSJ_SJ') == flag) {
        checkRight(flag, ['PMZBWJPSB_JSFX', 'PMZBWJPSB_ZQYWSP', 'PMZBWJPSB_ZQSYTJ', 'PMZBWJPSB_ZQYWCF', 'PMZBWJPSB_ZLQXZRCD', 'PMZBWJPSB_SJBZ']);
    }
    if ((name == 'ZBSJ_YS') == flag) {
        checkRight(flag, ['PMZBWJPSB_YFKED', 'PMZBWJPSB_JDKZFED', 'PMZBWJPSB_JDKZFSX', 'PMZBWJPSB_JSWKZFSJ', 'PMZBWJPSB_SJBGFYZFSJ', 'PMZBWJPSB_LYDBED', 'PMZBWJPSB_LYDBXJDB']);
    }
    if ((name == 'ZBSJ_ZJ') == flag) {
        checkRight(flag, ['PMZBWJPSB_FPLXSL', 'PMZBWJPSB_JYMSSSFX', 'PMZBWJPSB_CWBZ']);
    }
    if ((name == 'ZBSJ_FL') == flag) {
        checkRight(flag, ['PMZBWJPSB_FBRWYFZ', 'PMZBWJPSB_CBRWYFZ', 'PMZBWJPSB_HTSXYD', 'PMZBWJPSB_ZYJJFS', 'PMZBWJPSB_HTJCTJ', 'PMZBWJPSB_HTZR', 'PMZBWJPSB_BKKL', 'PMZBWJPSB_ZBWJHFX', 'PMZBWJPSB_FLBZ']);
    }
    if ((name == 'ZBSJ_CB') == flag) {
        checkRight(flag, ['PMZBWJPSB_GCCBNRFW', 'PMZBWJPSB_JGTJ', 'PMZBWJPSB_JJFS', 'PMZBWJPSB_GCLQDFS', 'PMZBWJPSB_GCLQDFSHL', 'PMZBWJPSB_JSSHMSQC', 'PMZBWJPSB_JSSHHL', 'PMZBWJPSB_JSZQYQCF', 'PMZBWJPSB_CBBZ', 'PMZBWJPSB_SJBGJJFSHL', 'PMZBWJPSB_SJBGJJFS']);
    }

    //招标评价审核表（装饰）的权限设置
    if ((name == 'ZBZS_JY') == flag) {
        checkRight(flag, ['ZBWJPS_FBRZX', 'ZBWJPS_ZBWZX', 'ZBWJPS_JYBZ']);
    }
    if ((name == 'ZBZS_GC') == flag) {
        checkRight(flag, ['ZBWJPS_JSFX', 'ZBWJPS_GQYW', 'ZBWJPS_GQSYTJ', 'ZBWJPS_GQYCCF', 'ZBWJPS_GCZLZR', 'ZBWJPS_BXQ', 'ZBWJPS_GCBZ']);
    }
    if ((name == 'ZBZS_YS') == flag) {
        checkRight(flag, ['ZBWJPS_DZ', 'ZBWJPS_GCYFK', 'ZBWJPS_GCJDKZF', 'ZBWJPS_GCJDKZFSJ', 'ZBWJPS_JSWKZFSJ', 'ZBWJPS_BGSQQZSJ', 'ZBWJPS_BXKZF', 'ZBWJPS_YFKEDSJ', 'ZBWJPS_LYDB', 'ZBWJPS_LYBB', 'ZBWJPS_NNGGZ']);
    }
    if ((name == 'ZBZS_ZJ') == flag) {
        checkRight(flag, ['ZBWJPS_FPLXSL', 'ZBWJPS_JYSSFX', 'ZBWJPS_CWBZ']);
    }
    if ((name == 'ZBZS_FL') == flag) {
        checkRight(flag, ['ZBWJPS_FBRFZ', 'ZBWJPS_CBRFZ', 'ZBWJPS_HTSXYD', 'ZBWJPS_ZYJJFS', 'ZBWJPS_HTJCRTJ', 'ZBWJPS_JZTGTK', 'ZBWJPS_HTZR', 'ZBWJPS_BKKL', 'ZBWJPS_ZBWJHFX', 'ZBWJPS_FLBZ']);
    }
    if ((name == 'ZBZS_CB') == flag) {
        checkRight(flag, ['ZBWJPS_CBNRFW', 'ZBWJPS_JGTJ', 'ZBWJPS_JJFS', 'ZBWJPS_GCLFSQ', 'ZBWJPS_GCLQDFSQ', 'ZBWJPS_RGCLJGTZ', 'ZBWJPS_RGCLJGRZFS', 'ZBWJPS_JGBHFX', 'ZBWJPS_JGZFXFW', 'ZBWJPS_BGSQQZSJQ', 'ZBWJPS_BGQZQRSJ', 'ZBWJPS_JSFS', 'ZBWJPS_JSFSWKSJ', 'ZBWJPS_JSYQCF', 'ZBWJPS_BXGM', 'ZBWJPS_FNRSBYD', 'ZBWJPS_CLSBYD', 'ZBWJPS_CBBZ']);
    }

    //施工合同评价审核表（装饰）的权限设置
    if ((name == 'SGHT_JY') == flag) {
        checkRight(flag, ['SGHTPSB_FBRZXQY', 'SGHTPSB_FBRZXZG', 'SGHTPSB_GCNRFW']);
    }
    if ((name == 'SGHT_GC') == flag) {
        checkRight(flag, ['SGHTPSB_FXJS', 'SGHTPSB_GQYC', 'SGHTPSB_GQSY', 'SGHTPSB_YWCF', 'SGHTPSB_GCZLQX', 'SGHTPSB_YSRQ', 'SGHTPSB_ZCBNR', 'SGHTPSB_ZCBNRHL', 'SGHTPSB_BXQ']);
    }
    if ((name == 'SGHT_YS') == flag) {
        checkRight(flag, ['SGHTPSB_DZA', 'SGHTPSB_DZB', 'SGHTPSB_DZC', 'SGHTPSB_YFKEDA', 'SGHTPSB_YFKEDB', 'SGHTPSB_JDKZF', 'SGHTPSB_JSSHFSA', 'SGHTPSB_JSSHFSB', 'SGHTPSB_BGSQQZ', 'SGHTPSB_BXKZF', 'SGHTPSB_YFKED']);
    }
    if ((name == 'SGHT_ZJ') == flag) {
        checkRight(flag, ['SGHTPSB_LYDB', 'SGHTPSB_LYDBXJ', 'SGHTPSB_NMGGZ', 'SGHTPSB_GMFX']);
    }
    if ((name == 'SGHT_FL') == flag) {
        checkRight(flag, ['SGHTPSB_FBRWY', 'SGHTPSB_CBRWY', 'SGHTPSB_HTSXYD', 'SGHTPSB_ZYJJ', 'SGHTPSB_HTJC', 'SGHTPSB_CBSTGTK', 'SGHTPSB_HTZR', 'SGHTPSB_BKKL', 'SGHTPSB_YXSCQ', 'SGHTPSB_HTHFX']);
    }
    if ((name == 'SGHT_CB') == flag) {
        checkRight(flag, ['SGHTPSB_JGTJ', 'SGHTPSB_JJFS', 'SGHTPSB_GCLQDFS', 'SGHTPSB_GCLQDHL', 'SGHTPSB_RGCLTZFS', 'SGHTPSB_RGCLTZHL', 'SGHTPSB_JGFXFW', 'SGHTPSB_JGFXHL', 'SGHTPSB_BGSQQZQ', 'SGHTPSB_BGSQQZFW', 'SGHTPSB_JSZQX', 'SGHTPSB_FBRSB', 'SGHTPSB_FBRCLYD', 'SGHTPSB_ZYGCFB', 'SGHTPSB_HTHFXQ']);
    }

    if (count-- > 0) {
        process(!flag, name, count);
    }

}

/**
 * @function 查询函数
 * @param table 表名
 * @param rows 列名
 * @param where 查询条件
 */
function queryDB(table, rows, where, type, name) {

    //获取数据源
    var dbsrc = (typeof(dbGetSrc) == 'undefined') ? 'PM' : dbGetSrc;

    //获取返回结果
    var result = DealAjax.getJsonDataTable(dbsrc, table, rows, where);

    //处理返回结果集
    try {
        if (typeof(type) == 'undefined' || typeof(type) == 'null') {
            result = result['Rows'][0];
        } else if (type == 'array') {
            result = result['Rows'];
        } else if (type == 'full') {
            result = result;
        } else if (type == 'item') {
            result = result['Rows'][0][name]
        }
    } catch (error) {

    }

    return result;
}

/**
 * @function update函数
 * @param {*} table 
 * @param {*} rows 
 * @param {*} where 
 * @param {*} type 
 * @param {*} name 
 */
function updateDB(table, rows, where, type, name) {

    //获取数据源
    var dbsrc = (typeof(dbGetSrc) == 'undefined') ? 'PM' : dbGetSrc;

    //获取返回结果
    var result = DealAjax.getJsonDataTable(dbsrc, table, rows, where);

    //处理返回结果集
    try {

    } catch (error) {

    }

    return result;

}

/**
 * @function delete函数
 * @param {*} table 
 * @param {*} rows 
 * @param {*} where 
 * @param {*} type 
 * @param {*} name 
 */
function deleteDB(table, rows, where, type, name) {

}

/**
 * @function insert函数
 * @param {*} table 
 * @param {*} rows 
 * @param {*} where 
 * @param {*} type 
 * @param {*} name 
 */
function insertDB(table, rows, where, type, name) {

}


/**
 * @function 设置目录名称附属信息
 */
function loadCatalog() {

    //获取选择到的记录的FJM（分级码）, 计算查询条件SQL
    var code = JSON.parse($('#BZHCGSC_MLMC').attr('title'))[0]['BZHCGML_FJM'];
    //二级分级码（项目名称）
    var pcode = code.substring(0, 8);
    //三级分级码（专业）
    var tcode = code.substring(0, 12);
    //四级分级码（公司）
    var compcode = code.substring(0, 16);

    //查询项目名称SQL
    var cnameSQL = " AND BZHCGML_FJM = '{code}' AND BZHCGML_JS = 2 ".replace('{code}', pcode);
    //查询专业名称SQL
    var cdomainSQL = " AND BZHCGML_FJM = '{code}' AND BZHCGML_JS = 3 ".replace('{code}', tcode);
    //查询专业名称SQL
    var companySQL = " AND BZHCGML_FJM = '{code}' AND BZHCGML_JS = 4 ".replace('{code}', compcode);

    //通过SQL查询此记录的相关信息，catalogName为二级目录名，catalogDomain为三级目录名，catalogCompany为四级目录
    var catalogName = queryDB("PMBZHCGMLWH", "BZHCGML_MLMC NAME", cnameSQL);

    //通过SQL查询此记录的相关信息，catalogName为二级目录名，catalogDomain为三级目录名，catalogCompany为四级目录
    var catalogDomain = queryDB("PMBZHCGMLWH", "BZHCGML_MLMC NAME", cdomainSQL);

    //通过SQL查询此记录的相关信息，catalogName为二级目录名，catalogDomain为三级目录名，catalogCompany为四级目录
    var catalogCompany = queryDB("PMBZHCGMLWH", "BZHCGML_MLMC NAME", companySQL);

    //加载项目名称信息
    if (typeof catalogName != 'undefined' && typeof catalogName['NAME'] != 'undefined') {
        $('#BZHCGSC_XMXC').val(catalogName['NAME']);
    } else {
        $('#BZHCGSC_XMXC').val('');
    }

    //加载专业名称信息
    if (typeof catalogDomain != 'undefined' && typeof catalogDomain['NAME'] != 'undefined') {
        $('#BZHCGSC_ZY').val(catalogDomain['NAME']);
    } else {
        $('#BZHCGSC_ZY').val('');
    }

    //加载专业公司名称信息
    if (typeof catalogCompany != 'undefined' && typeof catalogCompany['NAME'] != 'undefined') {
        $('#BZHCGSC_SSZYGS').val(catalogCompany['NAME']);
    } else {
        $('#BZHCGSC_SSZYGS').val('');
    }

}

/**
 * @function 审批流程处理
 */
window.GetPageWfInfo = function(c) {

    try {

        var cxt = JSON.parse(c); //JSON反序列化
        var msg = 0;

        var state = $.url.param('workflowstate');

        if (typeof cxt['DictCustValue'] != 'undefined' && cxt.DictCustValue.length == 1) {
            msg = cxt.DictCustValue[0].Value;
        } else if (typeof cxt['DictCustValue'] != 'undefined' && cxt.DictCustValue.length == 2) {
            msg = cxt.DictCustValue[1].Value;
        }

        var result = btnsaveclk(true, false);
        if (typeof(result) == "undefined") {
            $.ligerDialog.success('审核成功！');
            return true;
        } else {
            if (msg == 1) {
                if (result) {
                    $.ligerDialog.success('审核成功！');
                    btnsaveclk(true, false);
                    return true;
                } else {
                    return false;
                }
            } else {
                $.ligerDialog.success('流程回退成功！');
                return true;
            }
        }

    } catch (e) {

    }

}

/**
 * @function Panel标签初始化
 */
function initPanel() {

    $("#panelmain").css("border-top", "none");
    $(".l-panel").css("border", "none");
    $("#panelmain").css("margin", "0");
    $("#panelmxtab").css("margin", "0");
    $("#panelmxtab").css("border-top", "none");
    $("#panelmain").css("border-bottom", "none");
    $("#panelmxtab").css("border-bottom", "none");
    $("#panelmxtab").css("border-left", "none");

}

/**
 * @function 设置标题函数
 */
function divTitle(name, fieldName, sqlwhere, title) {

    title = document.title;

    if (arguments.length == 1) {
        title = name;
    } else if (arguments.length == 3) {
        title = queryDB(name, fieldName + " NAME", sqlwhere, 'item', "NAME");
    }

    var dv = "<div style='margin:0px 0px 20px 0px;text-align:center;'><h1>" + title + "</h1><div>";

    $("#panelmain").prepend(dv);

}

/**
 * @function 概念方案:1->深化方案:2->扩初方案:3->施工图:4 设置必选
 * @param {*} pcode 设计启动会 主键ID 
 */
function setRequiredLink(pcode) {

    /*******************获取设计启动会中，概念方案->深化方案->扩初方案->施工图的勾选情况，并以此设置必选*******************/

    try {
        //获取对应设计启动会项目ID
        pcode = typeof(pcode) == 'undefined' ? $('#XMPS_XMID').val() || $('#XSSQ_XMID').val() : pcode;

        //获取设计启动会详细信息
        var titleInfo = $('#XMPS_XMMC').attr('title');

        //如果没有获取到设计启动会主键ID，则通过XMPS_XMMC字段的属性获取
        if ((typeof(titleInfo) != 'undefined' && typeof(titleInfo) != 'null') &&
            (typeof(pcode) == 'undefined' || typeof(pcode) == 'null' || pcode == '')) {
            pcode = JSON.parse(titleInfo)[0]['XMGZ_XMID'];
        }

        //如果任然没有获取到设计启动会主键ID，则直接返回
        if (typeof(pcode) == 'undefined' || typeof(pcode) == 'null' || pcode == '') {
            return false;
        }

        //查询项目名称SQL
        var qlinkSQL = " AND XMGZ_XMID = '{code}' ".replace('{code}', pcode);

        //通过SQL查询此记录的相关信息，catalogName为二级目录名，catalogDomain为三级目录名
        var qlinkValue = queryDB("PMPMXMGZ", "XMGZ_HXGZ NAME", qlinkSQL, 'item', "NAME");

        //如果是深化方案页面，判断深化方案和初扩方案是否勾选，如果是，则设置概念方案为必选
        if ($.url.param('styleid') == '6385cb9b539840dc998fd360484e673c') {
            if (_.contains(qlinkValue.split(','), '1') && _.contains(qlinkValue.split(','), '2')) {
                checkRequired(true, ["XMPS_GNFA"]);
            } else {
                checkRequired(false, ["XMPS_GNFA"]);
            }
        }

        //如果是扩初成果提交页面，判断深化方案和初扩方案是否勾选，如果是，则设置深化方案为必选
        if ($.url.param('styleid') == '6566232de1504147aa514ef5760e56d6') {
            if (_.contains(qlinkValue.split(','), '2') && _.contains(qlinkValue.split(','), '3')) {
                checkRequired(true, ["XSSQ_SHFA"]);
            } else {
                checkRequired(false, ["XSSQ_SHFA"]);
            }
        }

        //如果是施工图页面，判断深化方案和初扩方案是否勾选，如果是，则设置初扩方案为必选
        if ($.url.param('styleid') == '9d105850545c484d8af2d5da5e691df7') {
            if (_.contains(qlinkValue.split(','), '3') && _.contains(qlinkValue.split(','), '4')) {
                checkRequired(true, ["XSSQ_KCCG"]);
            } else {
                checkRequired(false, ["XSSQ_KCCG"]);
            }
        }

    } catch (error) {
        console.log(error);
    }

}

/**
 * @function 当承揽方式为内部项目时，设置地产项目技术经办人函数
 */
function setRequiredZCR(pcode) {

    try {

        //获取对应承揽方式
        pcode = typeof(pcode) == 'undefined' ? $('#XMPS_BH').val() : pcode;

        //获取设计启动会详细信息
        var titleInfo = $('#XMPS_XMMC').attr('title');

        //如果没有获取到设计启动会主键ID，则通过XMPS_XMMC字段的属性获取
        if ((typeof(titleInfo) != 'undefined' && typeof(titleInfo) != 'null') &&
            (typeof(pcode) == 'undefined' || typeof(pcode) == 'null' || pcode == '')) {
            pcode = JSON.parse(titleInfo)[0]['XMGZ_LB'];
        }

        //如果任然没有获取到设计启动会主键ID，则直接返回
        if (typeof(pcode) == 'undefined' || typeof(pcode) == 'null' || pcode == '') {
            return false;
        }

        //承揽方式为内部项目，设置经办人为必选
        if ("内部项目" == pcode.trim()) {
            checkRequired(true, ["XMPS_ZCR", "XSSQ_GSJSCR"]);
        } else {
            checkRequired(false, ["XMPS_ZCR", "XSSQ_GSJSCR"]);
        }

    } catch (e) {

    }

}

//标准化成果目录维护，展开/收缩二级目录
function collapseName() {

    //获取项目名称
    $("td[id$='BZHCGML_MLMC']").each(function(index, item) {
        var slength = $(item).find('.l-grid-row-cell-inner').find('.l-grid-tree-space').length;
        //如果是二级目录，则触发点击事件
        if (slength == 2) {
            //触发点击事件
            $(item).find('.l-grid-row-cell-inner').find('.l-grid-tree-link').click();
        }

    });

    //注意需要在simpleGrid.Config中添加属性
    //onLoaded:function(){collapseName();}

};